#!/usr/bin/bash

shellDir=$(cd "$(dirname "$0")";pwd)
oldDir=`pwd`

cd ${shellDir}
started=false
command="${shellDir}/installer"
port=8080

function freePassword() {
    # 定义目录
    Identity_Dir=~/.ssh

    # 生成私钥
    if [[ ! -f ${Identity_Dir}/id_rsa ]]; then
        ssh-keygen -t rsa -m PEM -f ${Identity_Dir}/id_rsa -q -N "" > /dev/null 2>&1
    fi

    # 设置免密
    if [[ ! -f ${Identity_Dir}/authorized_keys ]]; then
        cat ${Identity_Dir}/id_rsa.pub >> ${Identity_Dir}/authorized_keys
        chmod 600 ${Identity_Dir}/authorized_keys
    elif [[ -z $(grep $(cat ${Identity_Dir}/id_rsa.pub | awk '{print $2}') ${Identity_Dir}/authorized_keys) ]]; then
        cat /${Identity_Dir}/id_rsa.pub >> ${Identity_Dir}/authorized_keys
    fi

    # 创建文件
    if [[ ! -f ${Identity_Dir}/known_hosts ]]; then
        touch ${Identity_Dir}/known_hosts
        chmod 644 ${Identity_Dir}/known_hosts
    fi

    # 添加记录
    LOCAL_SSH_PORT=$(grep ^'Port' /etc/ssh/sshd_config | awk -F' ' '{print $NF}' | head -1)
    if [ -z "${LOCAL_SSH_PORT}" ] || [ "${LOCAL_SSH_PORT}" == "22" ]; then
        for i in $(ip add | grep -w inet | awk '{print $2}' | cut -d "/" -f 1); do
            if [[ -z $(grep "${i}" ${Identity_Dir}/known_hosts) ]]; then
                ssh-keyscan "${i}" 2>/dev/null | grep "ecdsa-sha2-nistp256" >> ${Identity_Dir}/known_hosts
            fi
        done
    else
        for i in $(ip add | grep -w inet | awk '{print $2}' | cut -d "/" -f 1); do
            if [[ -z $(grep "${i}" ${Identity_Dir}/known_hosts) ]]; then
                ssh-keyscan -p "${LOCAL_SSH_PORT}" "${i}" 2>/dev/null | grep "ecdsa-sha2-nistp256" >> ${Identity_Dir}/known_hosts
            fi
        done
    fi
}

function startup() {
    mkdir -p logs
    export INSTALLER_PORT=${port}
    export RUN_MODE=prod && nohup ${command} > ${shellDir}/logs/installer.log 2>&1 &

    sleep 1

    for i in {1..20}; do
        echo "判断安装器是否启动(${i})..."
        if [[ $(ss -lnt | grep -w ${port}) ]]; then
            started=true
            break
        fi
        sleep 5
    done

    if [[ x"$started" == "xtrue" ]]; then
        ps -ef|grep "${command}"|grep -v grep |awk '{print $2}' > ${shellDir}/logs/run.pid
        ips=`hostname -I`
        ipArr=(${ips// / })
        echo -e "\n启动成功，访问地址：http://${ipArr[0]}:${port}"
    else
        echo -e "\n启动失败。。。"
    fi
}

function main() {
    freePassword
    startup
}

main